import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio,Switch,TreeSelect, message } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import styles from '../style.less';

import CryptoJS from 'crypto-js';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';
import DataLang from './DataLang';
// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [picture2, setPicture2] = useState<any[]>([]);
  const [uploadChanged2, setUploadChanged2] = useState<boolean>(false);
  // const treeData = DataHelper.getTreeData(common)
  // const treeProps = {
  //   treeData,
  //   treeNodeFilterProp:"title",
  //   // onChange: this.handleCategoryChange,
  //   treeDefaultExpandAll: true,
  //   searchPlaceholder: '搜索值',
  //   style: { width: '100%' },
  // }
  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.cover_file_id   = picture[0].file_id
        fieldsValue.cover_file_url  = picture[0].file_url
      }
      if(picture2.length > 0){
        fieldsValue.banner_file_id   = picture2[0].file_id
        fieldsValue.banner_file_url  = picture2[0].file_url
      }
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      console.log("submit fields ", fieldsValue)
      let arr1 = [];
      siteNameJson.map(item =>{
        let obj = {
          key:item.key,
          lang_text:item.lang_text,
          lang_content:item.lang_content,
        };
        arr1.push(obj)
      })
      let arr2 = [];
      siteDescJson.map(item =>{
        let obj = {
          key:item.key,
          lang_text:item.lang_text,
          lang_content:item.lang_content,
        };
        arr2.push(obj)
      })
      fieldsValue.name_arr = JSON.stringify(arr1)
      fieldsValue.description_arr = JSON.stringify(arr2)
      // 如果更新成功之后，重置表单
      handleSubmit(fieldsValue).then((success:any) => {
        console.log('handleSubmit then success is ', success)
        if(success){
          form.resetFields()
          setPicture([])
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }
  const setUploadFile2 = (fileList: any) => {
    setUploadChanged2(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    const fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if (fileArr.length > 0) {
      setPicture2(fileArr)
      setPreviewImg(fileArr[0].file_url)
    } else if (fileArr.length === 0) {
      console.log('set picture []')
      setPicture2([])
    }
  }
  const parseDataItem = (key:any,options:any) => {
    // console.log(options);
    var obj:any = {};
    if(Array.isArray(options) && options.length>0){
      options.map(item=>{
        if(item.alias_key == key){
          obj = item;
        }
      })
    }
    return obj
  }

  // 初始化变量
  const token = BdHelper.getBdToken()
  const [nameListLang, setnameList] = useState<any>(common?.multilingualoption);
  const [dataLangModalVisible, handleDataModalVisible] = useState<boolean>(false);
  const [fieldTitle, setFieldTitle] = useState<any>('');
  const [siteDescJson, setSiteDescJson] = useState<any>(parseDataItem('site_name',dataFormValues) || []);
  const [siteNameJson, setSiteNameJson] = useState<any>(dataFormValues.nameArr || []);
  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.file_url)
  const defaultPicture2 = DataHelper.buildFileByUrl(dataFormValues.rule)
  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadButton2 = DataHelper.showUploadBtn(isUpdate, picture2, defaultPicture2, uploadChanged2)
  // 表单提交
const handleSubmitDataForm = (value:any,title:any) => {
  console.log(value,241)
  setnameList(value)
  if(title == "name"){
    setSiteNameJson(value);
    console.log(2,45)
  }else if(title == "desc"){
    setSiteDescJson(value);
    console.log(4,56)
  }
  handleDataModalVisible(false)
}

  const userInfo = localStorage.getItem('user-login-info');
  let fresnsClient = eval("(" + userInfo + ")");
  const timestamp = new Date().getTime().toString().substr(0,10);
  var md5String = `appId=${fresnsClient?.app_id}&platform=${fresnsClient?.platform}&timestamp=${timestamp}&key=${fresnsClient?.app_secret}`;

  // 弹出框
  // @ts-ignore
  return <Modal
   className={styles.input}
    destroyOnClose
    title={isUpdate?'编辑':'新建'}
    width={DataHelper.DEFAULT_MODAL_WIDTH}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >
    {/* <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="父级分类" help="默认为一级分类">
      {form.getFieldDecorator('parent_id', {
        initialValue: isUpdate ? dataFormValues.parent_id : [],
      })(<TreeSelect placeholder="请选择" {...treeProps} />)}
    </FormItem> */}
     <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'ranknum' })}>
      {form.getFieldDecorator('rank_num', {
        initialValue: isUpdate ? dataFormValues.rank_num : 888,
        // rules: [],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }}/>)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}  label={'分类名称'}>
            {form.getFieldDecorator('name', {
               initialValue: siteNameJson.length>0?siteNameJson[0].lang_content:'',
              rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input readOnly 
              onClick={() => {
                setFieldTitle('name');
                if(siteNameJson && siteNameJson.length>0){
                  setnameList(siteNameJson);
                }else{
                  setnameList(JSON.parse(JSON.stringify(common?.multilingualoption)));
                }
                handleDataModalVisible(true);
               }}
      />)}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}  label={'分类描述'}>
            {form.getFieldDecorator('desc', {
               initialValue: siteDescJson.length>0?siteDescJson[0].lang_content:'',
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input readOnly 
              onClick={() => {
                setFieldTitle('desc');
                if(siteDescJson && siteDescJson.length>0){
                  setnameList(siteDescJson);
                }else{
                  setnameList(JSON.parse(JSON.stringify(common?.multilingualoption)));
                }
                handleDataModalVisible(true);
               }}
      />)}
          </FormItem>
    {/* <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'父级分类'} help="默认为一级分类">
      {form.getFieldDecorator('parent_id', {
        initialValue: isUpdate ? (dataFormValues.parent_id).toString() : undefined,
        //  rules: [{ required: true, message: '请选择！',}],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.treeData && TsxHelper.buildSelectOption(common.treeData)}
      </Select>)}
    </FormItem> */}
 <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'分类图标'}>
      {form.getFieldDecorator('picture', {
        // initialValue: defaultPicture,
        // rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/tweetfiles/upload"
          defaultFileList={defaultPicture}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ type: 'image' }}
          onRemove={() => setPicture([])}
          onChange={(changeObj) => setUploadFile(changeObj.fileList)}
          onPreview={() => handlePreviewModalVisible(true)}
          headers={{
            Authorization: `Bearer ${token}`,
            'platform': fresnsClient?.platform,
            'timestamp': timestamp,
            'appId': fresnsClient?.app_id,
            'sign':  CryptoJS.MD5(md5String).toString(),
          }}
        >
          {
            showUploadButton ? (
              <Button>
                <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'分类条幅'}>
      {form.getFieldDecorator('picture2', {
        // initialValue: defaultPicture,
        // rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/tweetfiles/upload"
          defaultFileList={defaultPicture2}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ type: 'image' }}
          onRemove={() => setPicture2([])}
          onChange={(changeObj) => setUploadFile2(changeObj.fileList)}
          onPreview={() => handlePreviewModalVisible(true)}
          headers={{
            Authorization: `Bearer ${token}`,
            'platform': fresnsClient?.platform,
            'timestamp': timestamp,
            'appId': fresnsClient?.app_id,
            'sign':  CryptoJS.MD5(md5String).toString(),
          }}
        >
          {
            showUploadButton2 ? (
              <Button>
                <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>
    
      

     <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='是否启用'>
          {form.getFieldDecorator('is_enable', {
            initialValue: isUpdate ? dataFormValues.is_enable : '',
            valuePropName: 'checked',
            rules: [],
          })(<Switch checkedChildren={formatMessage({ id: 'app.base.is-enable.true' })} unCheckedChildren={formatMessage({ id: 'app.base.is-enable.close' })} />)}
        </FormItem> 

    {/* <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      '启用状态'
    }>
      {form.getFieldDecorator('language_status', {
        initialValue: isUpdate ? dataFormValues?.language_status && (dataFormValues?.language_status).toString() : '2',
        // rules: [{ required: true, message: '请选择！',}],
      })(<Radio.Group buttonStyle="solid">
          <Radio value={'2'}>不启用</Radio>
          <Radio value={'1'}>启用</Radio>
        </Radio.Group>
      )}
    </FormItem> */}
      <DataLang
        dataModalVisible={dataLangModalVisible}
        isUpdate={isUpdate}
        dataFormValues={dataFormValues}
        common={common || {}}
        // name={modalName}
        nameList={nameListLang}
        title={fieldTitle}
        onSubmit={handleSubmitDataForm}
        onCancel={() => handleDataModalVisible(false)}
    />
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
